import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm, Button } from 'antd';
import Factory from '../../factory';
import * as datetime from '../../../utils/datetime'
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
import dataImportCreate from '../../addons/DataImport'
import * as menuService from '../../../services/menus';
import numeral from 'numeral';
const daoName = "BaseAsseFYZJ";
const ButtonGroup = Button.Group;
const renderNumber = (num) => {
    let value = ''
    if (num) {
        value = numeral(num).format('0,0.00')
    }
    return value
};
const columns = [
    { title: '日期', width: 100, sorter: true, key: 'DTID', caption: "DTID", render: data => datetime.format(data.DTID, "yyyy-MM-dd"), dispaly: true, filter: true, canEdit: true },
    { title: '部门', width: 85, sorter: true, key: 'UTID', dataIndex: 'UTNM', dispaly: true, filter: true },
    { title: '员工', width: 85, sorter: true, key: 'EMID', dataIndex: 'EMNM', dispaly: true, filter: true },
    { title: '费用增减额', width: 85, className: "column-money", sorter: true, render: data => renderNumber(data.FYEJ), key: 'FYEJ', dispaly: true, filter: true },
    { title: '说明', width: 300, sorter: true, dataIndex: 'EXPL', key: 'EXPL', dispaly: true, filter: true },
];
const controls = [
    { name: "DTID", required: true, label: "日期", type: "date", grid: 12 / 24, dataType: "date" },
    {
        name: "UTID", label: "部门", type: "tree-select", grid: 12 / 24, required: true,
        fetch: { daoName: "Organization", optionTpl: 'Name', valueTpl: "ID", parentTpl: "ParentID" },
        dataType: "number", seekType: 2, placeholder: '请选择所属部门...'
    },
    {
        name: "EMID", label: "员工", type: "tree-select", grid: 12 / 24, required: true,
        dataType: "number", fetch: { daoName: "User", optionTpl: 'Name', valueTpl: "ID" }
    },
    { name: "FYEJ", label: "费用增减", required: true, type: "number", dataType: "number", grid: 12 / 24 },
    { name: "EXPL", label: "说明", type: "text", grid: 24 / 24, layout: { labelSpan: 3, wrapperSpan: 20 } },
]
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
const DataImport = dataImportCreate(daoName);
class JFZJWHForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataChange: false
        };
    }
    componentDidMount() {
        this.props.dispatch({
            type: `${daoName}/setKeyName`,
            payload: { keyName: "ID", permID: this.props.permID }
        });
        let sort = {
            field: 'DTID',
            order: 'descend'
        }
        this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, page: 1, pageSize: 20, sorter: sort }
        });
        this.loadOptionData();
    }
    loadOptionData() {
        let options = []
        controls.map(c => {
            if (c.fetch) {
                let f = c.fetch;
                if (c.type === 'cascader-select') {
                    f.isCascader = true;
                }
                if (c.type !== 'search') {
                    options.push(f);
                }
            }
        })
        if (daoName && options.length > 0) {
            this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
        }
    }
    showModelHandler(isAdd) {
        let key = null
        if (!isAdd) {
            const len = this.props.selectedRowKeys.length;
            if (len === 0) {
                message.info('请选择要编辑的行，如果选择了多行，则使用最后一次选择！');
                return;
            }
            key = this.props.selectedRowKeys[len - 1]
        }
        this.props.dispatch({
            type: `${daoName}/openEdit`,
            payload: { key }
        });
    }
    deleteHandler() {
        const keys = this.props.selectedRowKeys;
        const len = keys.length;
        if (len === 0) {
            message.info('请选择要删除的行！');
            return;
        }
        Modal.confirm({
            title: '提示',
            content: `你确认要删除选中的${len}行数据吗？`,
            okText: '删除',
            cancelText: '取消',
            onOk: () => {
                this.props.dispatch({
                    type: `${daoName}/remove`,
                    payload: { daoName, keys },
                });
            }
        });
    }
    edidOkHandler() {
        const form = this.refs.userForm.getForm()
        form.validateFields((err, values) => {
            if (!err) {
                let t = `${daoName}/create`
                const { keyName, record } = this.props;
                let msg = "数据添加成功！"
                if (record[keyName]) {
                    values[keyName] = record[keyName];
                    t = `${daoName}/patch`
                    msg = "数据修改成功！"
                }
                controls.map((c, i) => {
                    if (c.type === 'cascader-select') {
                        let vs = values[c.name];
                        if (vs.length > 0) {
                            values[c.name] = vs[vs.length - 1];
                        } else {
                            values[c.name] = null;
                        }
                    }
                    if (c.dataType === "number") {
                        values[c.name] = Number(values[c.name])
                    } else if (c.dataType === "date" || c.dataType === "datetime") {
                        values[c.name] = !values[c.name] ? null : new Date(values[c.name])
                    } else {
                        values[c.name] = values[c.name] === undefined ? null : values[c.name]
                    }
                    if (c.multiple || c.type === 'checkbox-group') {
                        values[c.name] = values[c.name].join(',');
                    }
                })
                this.state.dataChange = true;
                this.props.dispatch({
                    type: t,
                    payload: { daoName, values },
                })
            }
        });
    };
    hideEditHandler() {
        const form = this.refs.userForm.getForm();
        form.resetFields();
        if (this.state.dataChange) {
            this.props.dispatch({
                type: `${daoName}/reload`,
                payload: { daoName },
            });
            this.state.dataChange = false;
        }
        this.props.dispatch({
            type: `${daoName}/hideEdit`
        });
    };
    showImportHandler() {
        this.props.dispatch({
            type: `${daoName}_DataImport/setDisplay`,
            payload: { display: true },
        });
    }
    render() {
        let { showEdit, record, showImport, permID, popedomTypes } = this.props
        const pTypes = popedomTypes[permID]
        let data = null
        if (pTypes.indexOf("2") !== -1) {
            data = <ButtonGroup style={{ zIndex: 0 }}>
                <Button onClick={this.showModelHandler.bind(this, true)}>新增</Button>
                <Button onClick={this.showModelHandler.bind(this, false)}>修改</Button>
                <Button onClick={this.deleteHandler.bind(this)}>删除</Button>
            </ButtonGroup>
        }
        return (
            <div style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
                <div>
                    <div>
                        {data}
                    </div>
                    <Modal title="绩费增减" width={700} visible={showEdit} onOk={this.edidOkHandler.bind(this)} onCancel={this.hideEditHandler.bind(this)}
                        footer={[
                            <Button key="close" type="ghost" onClick={this.hideEditHandler.bind(this)}>关闭</Button>,
                            <Button key="submit" type="primary" onClick={this.edidOkHandler.bind(this)}>保存</Button>
                        ]}
                    >
                        <EditFrom ref="userForm" daoName={daoName} controls={controls} record={record} />
                    </Modal>
                    <DataTable ref="userTable" daoName={daoName} columns={columns} controls={controls} permID={permID} />
                    <DataImport title="绩费增减" importName="BaseAsseFYZJ" daoName="BaseAsseFYZJ" controls={controls} />
                </div>
            </div>
        )
    }
}

function mapStateToProps(state) {
    const { showEdit, record, selectedRowKeys, keyName } = state[daoName];
    const { userID, orgID, pOrgID, popedomTypes } = state.menus;
    const { display } = state[`${daoName}_DataImport`];
    return {
        userID,
        orgID,
        pOrgID,
        popedomTypes,
        showEdit,
        selectedRowKeys,
        keyName,
        record,
        showImport: display
    }
}
JFZJWHForm = connect(mapStateToProps)(JFZJWHForm)
export default JFZJWHForm;

let render = (props) => React.createElement(JFZJWHForm, props);
let f = new Factory()
f.set("JFZJWHForm", render)
